
package com.ikamobile.flickrer;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.util.Log;
import android.widget.RemoteViews;

import java.io.FileNotFoundException;

public class PhotoWidgetProvider extends AppWidgetProvider {

    private static final String ACTION_SWITCH_PHOTO = "flickrer.SWITCH_PHOTO";
    private static final String LOG_TAG = PhotoWidgetProvider.class.getSimpleName();

    @Override
    public void onReceive(Context context, Intent intent) {
        if (ACTION_SWITCH_PHOTO.equals(intent.getAction())) {
            AppWidgetManager am = AppWidgetManager.getInstance(context);
            RemoteViews rv = new RemoteViews(context.getPackageName(),
                    R.layout.photo_widget);
            updatePhoto(new PhotoHelper(context), rv);
            int wid = Integer.parseInt(intent.getData().getHost());
            am.updateAppWidget(wid, rv);
        } else
            super.onReceive(context, intent);
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
            int[] appWidgetIds) {
        PhotoHelper photoHelper = new PhotoHelper(context);
        for (int wid : appWidgetIds) {
            RemoteViews rv = new RemoteViews(context.getPackageName(),
                    R.layout.photo_widget);
            updatePhoto(photoHelper, rv);
            Intent intent = new Intent(ACTION_SWITCH_PHOTO, Uri.parse("flickrerwidget://" + wid));
            PendingIntent pendingIntent =
                        PendingIntent.getBroadcast(context, 0, intent,
                                PendingIntent.FLAG_UPDATE_CURRENT);
            rv.setOnClickPendingIntent(R.id.photo, pendingIntent);
            appWidgetManager.updateAppWidget(wid, rv);
        }
    }

    private void updatePhoto(PhotoHelper photoHelper, RemoteViews rv) {
        try {
            Bitmap bitmap = photoHelper.loadRandomCachedPhoto();
            if (bitmap != null) {
                rv.setImageViewBitmap(R.id.photo, bitmap);
            }
        } catch (FileNotFoundException e) {
            Log.e(LOG_TAG, "failed to load bitmap", e);
        }
    }
}
